<?php

class FComponent
{
    
    private $extJsComponent;
    
    protected $layout;
    
    protected $items;
 
    public function __construct($extJsComponent)
    {
        $this->extJsComponent = $extJsComponent;
    }
    
    public function generate()
    {
        $jsCode = " Ext.create('{$this->getExtJsComponent()}', { ";
        
        if ( strlen($this->getLayout()) > 0 )
        {
            $jsCode .= " layout: '{$this->getLayout()}', ";
        }
        
        // Items
        $jsCode .= ' items: [ ';
        foreach ( $this->getItems() as $item )
        {
            if ( $item instanceof FWidget )
            {
                $jsCode .= $item->generate() . ',';
            }
        }
        $jsCode .= ' ],';
        
        $jsCode .= " }); ";
        
        $jsCode .= $this->addEvents($this->getItems());
        
        return $jsCode;
    }
    
    private function addEvents($items)
    {
        $jsCode = '';
        
        foreach ( $items as $item )
        {
            if ( $item instanceof FWidget )
            {
                $jsCode .= $item->addEvents();
            }
            
            if ( method_exists($item, 'getItems') )
            {
                if ( count($item->getItems()) > 0 )
                {
                    $jsCode .= $this->addEvents($item->getItems());
                }
            }
        }
        
        return $jsCode;
    }
    
    public function getLayout() {
        return $this->layout;
    }

    public function setLayout($layout) {
        $this->layout = $layout;
    }

    public function getItems() {
        return $this->items;
    }
    
    public function addItem($item)
    {
        $this->items[] = $item;
    }
    
    public function getExtJsComponent() {
        return $this->extJsComponent;
    }

    public function setExtJsComponent($extJsComponent) {
        $this->extJsComponent = $extJsComponent;
    }
    
}

?>
